package com.hao.wms.service.impl;

import com.hao.wms.dao.IStockIncomeBillDao;
import com.hao.wms.domain.StockIncomeBill;
import com.hao.wms.domain.StockIncomeBillItem;
import com.hao.wms.query.PageResult;
import com.hao.wms.query.QueryObject;
import com.hao.wms.service.IProductStockService;
import com.hao.wms.service.IStockIncomeBillService;
import com.hao.wms.util.UserContext;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

public class StockIncomeBillServiceImpl implements IStockIncomeBillService {
    private IStockIncomeBillDao dao;
    private IProductStockService productStockService;


    public void setDao(IStockIncomeBillDao dao) {
        this.dao = dao;
    }

    public void setProductStockService(IProductStockService productStockService) {
        this.productStockService = productStockService;
    }

    @Override
    public void save(StockIncomeBill stockIncomeBill) {
        stockIncomeBill.setInputUser(UserContext.getUser());
        stockIncomeBill.setInputTime(new Date());
        stockIncomeBill.setStatus(StockIncomeBill.NORMAL);
        parseItems(stockIncomeBill);
        dao.save(stockIncomeBill);

    }

    private void parseItems(StockIncomeBill stockIncomeBill) {
        stockIncomeBill.setTotalNumber(BigDecimal.ZERO);
        stockIncomeBill.setTotalAmount(BigDecimal.ZERO);
        for (StockIncomeBillItem item : stockIncomeBill.getItems()) {
            item.setBill(stockIncomeBill);
            item.setAmount(item.getCostPrice().multiply(item.getNumber()).setScale(2, BigDecimal.ROUND_HALF_UP));
            stockIncomeBill.setTotalNumber(stockIncomeBill.getTotalNumber().add(item.getNumber()));
            stockIncomeBill.setTotalAmount(stockIncomeBill.getTotalAmount().add(item.getAmount()));
        }
    }

    @Override
    public void update(StockIncomeBill stockIncomeBill) {
        if (stockIncomeBill.getStatus() == StockIncomeBill.NORMAL) {
            parseItems(stockIncomeBill);
            dao.update(stockIncomeBill);
        }

    }

    @Override
    public void delete(StockIncomeBill stockIncomeBill) {
        dao.delete(stockIncomeBill);

    }

    @Override
    public StockIncomeBill get(Long id) {
        return dao.get(id);
    }

    @Override
    public List<StockIncomeBill> list() {
        return dao.list();
    }

    @Override
    public PageResult query(QueryObject qo) {
        return dao.query(qo);
    }

    @Override
    public void audit(Long id) {
        StockIncomeBill bill = dao.get(id);
        if(bill.getStatus()==StockIncomeBill.NORMAL){
            bill.setAuditor(UserContext.getUser());
            bill.setAuditTime(new Date());
            bill.setStatus(StockIncomeBill.AUDIT);
            for (StockIncomeBillItem item : bill.getItems()) {
                productStockService.income(bill.getDepot(),item.getProduct(),item.getNumber(),item.getCostPrice());
            }
            dao.update(bill);
        }
    }
}
